package cn.com.libertymutual.production.service.impl.business;

import cn.com.libertymutual.production.model.nomorcldatasource.*;
import cn.com.libertymutual.production.pojo.request.LinkKindRequest;
import cn.com.libertymutual.production.pojo.request.PrpdKindLibraryRequest;
import cn.com.libertymutual.production.pojo.request.PrpdRiskRequest;
import cn.com.libertymutual.production.pojo.response.Response;
import cn.com.libertymutual.production.service.api.business.RiskBusinessService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 事务管理注意事项：
 * 1. 新增/修改操作必须启用事务
 * 2. 方法体内部抛出异常即可启用事务
 * @author Steven.Li
 * @date 2017年7月28日
 * 
 */
@Service
@Transactional(rollbackFor = Exception.class, transactionManager = "transactionManagerCoreData")
public class RiskBusinessServiceImpl extends RiskBusinessService {

	@Override
	public Response checkRiskCodeUsed(String riskcode) {
		Response result = new Response();
		try {
			boolean isUsed = prpdRiskService.cheakRiskCodeUsed(riskcode);
			result.setResult(isUsed);
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	@Override
	public Response insert(PrpdRiskRequest request) throws Exception {
		Response result = new Response();
		Prpdrisk record = new Prpdrisk();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		try {
			//保存prpdrisk
			BeanUtils.copyProperties(request, record);
			record.setNewriskcode(request.getRiskcode());
			record.setSaleenddate(sdf.parse("2099/12/31"));
			record.setEnddateflag("N");
			record.setEffectivestartdate(sdf.parse("2010/1/1"));
			record.setInvalidenddate(sdf.parse("2099/12/31"));
			prpdRiskService.insert(record);

			//保存Fdriskconfig
			Fdriskconfig fdriskconfig = new Fdriskconfig();
			fdriskconfig.setUwyear("0000");
			fdriskconfig.setRiskcode(request.getRiskcode());
			fdriskconfig.setStartdate(new SimpleDateFormat("yyyy/MM/dd").parse("1900/1/1"));
			fdriskconfig.setEnddate(new SimpleDateFormat("yyyy/MM/dd").parse("9999/1/1"));
			fdriskconfig.setCodetype("DangerSplitMode");
			fdriskconfig.setCodevalue(request.getDangerSplitMode());
			fdriskconfigService.insert(fdriskconfig);
			fdriskconfig.setCodetype("DangerViewType");
			fdriskconfig.setCodevalue(request.getDangerViewType());
			fdriskconfigService.insert(fdriskconfig);
			fdriskconfig.setCodetype("ReinsTrialMode");
			fdriskconfig.setCodevalue(request.getReinsTrialMode());
			fdriskconfigService.insert(fdriskconfig);
			fdriskconfig.setCodetype("RiskEvaluateMode");
			fdriskconfig.setCodevalue(request.getRiskEvaluateMode());
			fdriskconfigService.insert(fdriskconfig);
			fdriskconfig.setCodetype("RiskPoolMode");
			fdriskconfig.setCodevalue(request.getRiskPoolMode());
			fdriskconfigService.insert(fdriskconfig);

			//保存Fhrisk
			Fhrisk fhrisk = new Fhrisk();
			fhrisk.setRiskcode(request.getRiskcode());
			request.getFhData().forEach(e -> {
				fhrisk.setTreatyno(e.getFhtreaty());
				fhrisk.setSectionno(e.getFhsection());
				fhrisk.setInrateflag(e.getInrateflag());
				fhriskService.insert(fhrisk);
			});

			//保存Fhxrisk
			FhxriskKey fhxrisk = new FhxriskKey();
			fhxrisk.setRiskcode(request.getRiskcode());
			request.getFhxData().forEach(e->{
				fhxrisk.setTreatyno(e.getFhxtreaty());
				fhxrisk.setLayerno(new BigDecimal(e.getFhxlayer()));
				fhxrisk.setSectionno(e.getFhxsection());
				fhxriskService.insert(fhxrisk);
			});

			//保存Fhexitemkind
			Fhexitemkind fhexitemkind = new Fhexitemkind();
			fhexitemkind.setRiskcode(request.getRiskcode());
			request.getFhData().forEach(e1->{
				fhexitemkind.setTreatyno(e1.getFhtreaty());
				fhexitemkind.setSectionno(e1.getFhsection());
				e1.getFhexitemkindArray().forEach(e2 -> {
					fhexitemkind.setItemkind(e2.getItemkind());
					fhexitemkind.setItemkinddesc(e2.getItemkinddesc());
					fhexitemkindService.insert(fhexitemkind);
				});
			});

		} catch (Exception e) {
			log.error("系统异常错误！", e);
			throw e;
		}
		return result;
	}

	@Override
	public Response update(PrpdRiskRequest request) throws Exception {
		Response result = new Response();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		try {
			List<Prpdrisk> list = prpdRiskService.fetchRisks(request);
			Prpdrisk record = new Prpdrisk();
			BeanUtils.copyProperties(request, record);
			//判断是否升级版本
			if(list != null && !list.isEmpty()) {
				prpdRiskService.update(record);
			} else {
				record.setNewriskcode(request.getRiskcode());
				record.setSaleenddate(sdf.parse("2099/12/31"));
				record.setEnddateflag("N");
				record.setEffectivestartdate(sdf.parse("2010/1/1"));
				record.setInvalidenddate(sdf.parse("2099/12/31"));
				//Max说升级版本后原版本让用户手动修改状态值
				prpdRiskService.insert(record);
			}
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			throw e;
		}
		return result;
	}

	@Override
	public Response linkKind(LinkKindRequest request) throws Exception {
		Response result = new Response();
		PrpdRiskRequest prpdRiskRequest = request.getRisk();
		List<PrpdKindLibraryRequest> kinds = request.getSelectedRows();
		Prpdkind record = new Prpdkind();
		try {
			record.setRiskcode(prpdRiskRequest.getRiskcode());
			record.setRiskversion(prpdRiskRequest.getRiskversion());
			record.setShortratetype(request.getShortratetype());
			record.setPlancode("defaultPlan");
			for(PrpdKindLibraryRequest kind : kinds) {
				record.setKindcode(kind.getKindcode());
				record.setKindversion(kind.getKindversion());
				record.setKindcname(kind.getKindcname());
				record.setKindename(kind.getKindename());
				record.setStartdate(kind.getStartdate());
				record.setEnddate(kind.getEnddate());
				record.setCalculateflag(kind.getCalculateflag());
				record.setNewkindcode(kind.getNewkindcode());
				record.setValidstatus(kind.getValidstatus());
				record.setShortratetype(kind.getShortratetype());
				//如果是组合险
				if("1".equals(prpdRiskRequest.getCompositeflag())) {
					record.setOwnerriskcode(kind.getOwnerriskcode());
				} else {
					record.setOwnerriskcode(prpdRiskRequest.getRiskcode());
				}
				prpdKindService.insert(record);
			}
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			throw e;
		}
		return result;
	}

	@Override
	public Response queryAllFhtreaty() {
		Response result = new Response();
		try {
			Fhtreaty criteria = new Fhtreaty();
			criteria.setUwyear(LocalDate.now().getYear()+"");
			List<Fhtreaty> fhtreaties = fhtreatyService.findAll(criteria);
			result.setResult(fhtreaties);
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	@Override
	public Response queryFhsections(String treatyno) {
		Response result = new Response();
		try {
			List<Fhsection> fhsections = fhsectionService.findByTreatyNo(treatyno);
			result.setResult(fhsections);
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	@Override
	public Response queryFhexitemkinds(String treatyno, String sectionno) {
		Response result = new Response();
		try {
			List<Fhexitemkind> fhexitemkinds = fhexitemkindService.findAll(treatyno, sectionno);
			List<Fhexitemkind> rs = new ArrayList<>();
			if (fhexitemkinds != null && fhexitemkinds.size() > 0) {
				Map<String, List<Fhexitemkind>> fhexitemkindsCollects = fhexitemkinds
						.stream()
						.collect(Collectors.groupingBy(Fhexitemkind::getItemkind));
				fhexitemkindsCollects.forEach((key, value) -> rs.add(value.get(0)));
			}
			rs.sort((f1,f2) -> f1.getItemkind().compareToIgnoreCase(f2.getItemkind()));
			result.setResult(rs);
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	@Override
	public Response queryAllFhxtreaty() {
		Response result = new Response();
		try {
			Fhxtreaty criteria = new Fhxtreaty();
			criteria.setUwyear(LocalDate.now().getYear()+"");
			List<Fhxtreaty> fhxtreaties = fhxtreatyService.findAll(criteria);
			result.setResult(fhxtreaties);
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	@Override
	public Response queryFhxlayers(String treatyno) {
		Response result = new Response();
		try {
			List<Fhxlayer> fhxlayers = fhxlayerService.findAll(treatyno);
			result.setResult(fhxlayers);
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	@Override
	public Response queryFhxsections(String treatyno, String layerno) {
		Response result = new Response();
		try {
			List<Fhxsection> fhxsections = fhxsectionService.findAll(treatyno, layerno);
			result.setResult(fhxsections);
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	@Override
	public Response queryFdriskconfigByRisk(String riskcode) {
		Response result = new Response();
		try {
			List<Fdriskconfig> fdriskconfigs = fdriskconfigService.findByRisk(riskcode);
			result.setResult(fdriskconfigs);
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	@Override
	public Response queryFhriskByRisk(String riskcode) {
		Response result = new Response();
		try {
			List<Fhrisk> fhrisks = fhriskService.findByRisk(riskcode);
			result.setResult(fhrisks);
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	@Override
	public Response queryFhexitemkindByRisk(String riskcode) {
		Response result = new Response();
		try {
			List<Fhexitemkind> fhexitemkinds = fhexitemkindService.findByRisk(riskcode);
			result.setResult(fhexitemkinds);
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	@Override
	public Response queryFhxriskByRisk(String riskcode) {
		Response result = new Response();
		try {
			List<FhxriskKey> fhxrisks = fhxriskService.findByRisk(riskcode);
			result.setResult(fhxrisks);
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}

	@Override
	public Response queryRiskByCodes(List<String> riskcodes) {
		Response result = new Response();
		try {
			List<Prpdrisk> prpdrisks = prpdRiskService.queryRiskByCodes(riskcodes);
			result.setResult(prpdrisks);
			result.setSuccess();
		} catch (Exception e) {
			log.error("系统异常错误！", e);
			result.setAppFail();
			result.setResult(e.getMessage());
		}
		return result;
	}
}
